/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback } from '../../Index';
import { ViewTreeTool } from '../../utils/checker/ViewTreeTool';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'SetListSizeInScrollCheck');
let viewTreeTool: ViewTreeTool = new ViewTreeTool();
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: 'docs/set-list-size-in-scroll-check.md',
    description: 'When using `LazyForEach` to load child components in a `List`, if the width and height of the `List` are not set, all child components will be loaded.'
};
interface WarnInfo {
    lineNum: number;
    startCol: number;
    endCol: number;
    filePath: string;
};

export class SetListSizeInScrollCheck implements BaseChecker {
  readonly metaData: BaseMetaData = gMetaData;
  public rule: Rule;
  public defects: Defects[] = [];
  public issues: IssueReport[] = [];

  private clsMatcher: ClassMatcher = {
    matcherType: MatcherTypes.CLASS,
    hasViewTree: true,
  };

  public registerMatchers(): MatcherCallback[] {
    const matchClazzCb: MatcherCallback = {
      matcher: this.clsMatcher,
      callback: this.check,
    };
    return [matchClazzCb];
  }

  public check = (target: ArkClass): void => {
    if (!viewTreeTool.hasTraverse(target)) {
      let viewTreeRoot = target.getViewTree()?.getRoot();
      if (!viewTreeRoot) {
        return;
      }
      if (viewTreeRoot.name !== 'Scroll') {
        return;
      }
      for (const child of viewTreeRoot.children) {
        if (child.name !== 'List') {
          continue;
        }
        if (child.attributes.has('width') && child.attributes.has('height')) {
          continue;
        }
        const useLazyForEach = child.children.find(c => c.name === 'LazyForEach');
        if (!useLazyForEach) {
            continue;
        }
        const create = child.attributes.get('create');
        if (!create) {
            logger.error(`cannot find position of the List Component in arkClass: ${target.getSignature().toString()}`);
            continue;
        }
        const pos = create[0].getOriginPositionInfo();
        const lineNum = pos.getLineNo();
        const startCol = pos.getColNo();
        const endCol = pos.getColNo();
        const filePath = target.getDeclaringArkFile().getFilePath();
        this.addIssueReport({ lineNum, startCol, endCol, filePath });
      }
    }
  };

  private addIssueReport(warnInfo: WarnInfo): void {
    const severity = this.rule.alert ?? this.metaData.severity;
    if (warnInfo.lineNum !== -1) {
      let defects = new Defects(
        warnInfo.lineNum,
        warnInfo.startCol,
        warnInfo.endCol,
        this.metaData.description,
        severity,
        this.rule.ruleId,
        warnInfo.filePath,
        this.metaData.ruleDocPath,
        true,
        false,
        false
      );
      this.issues.push(new IssueReport(defects, undefined));
    }
  }
}